package com.itheima.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.controller.results.Code;
import com.itheima.controller.results.Result;
import com.itheima.domain.Student;
import com.itheima.service.StudentService;
import com.itheima.system.exception.BusinessException;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private StudentService studentService;
    @PostMapping
    public Result save(Student student){
        boolean save = studentService.save(student);
        return new Result(save ? Code.SAVE_OK:Code.SAVE_ERROR);
    }

    @PutMapping
    public Result update(Student student){
        boolean update = studentService.update(student);
        return new Result(update ? Code.UPDATE_OK:Code.UPDATE_ERROR);
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id){
        boolean delete = studentService.delete(id);
        if (id==3){
            throw new BusinessException("删除出错了",Code.DELETE_ERROR);
        }
        return new Result(delete?Code.DELETE_OK:Code.DELETE_ERROR);
    }

    @GetMapping("/{id}")
    public Result findId(@PathVariable Integer id){
        Student student = studentService.findById(id);
        return new Result(null != student ?Code.FIND_OK:Code.FIND_ERROR ,student);
    }

    @GetMapping("/{page}/{size}")
    public Result find(@PathVariable int page ,@PathVariable int size){
        PageInfo<Student> student = studentService.findAll(page, size);
        return new Result(null!=student ?Code.FIND_OK:Code.FIND_ERROR,student);
    }
}
